package com.opencee.cloud.msg.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.opencee.cloud.msg.api.constatns.HttpNotifyState;
import com.opencee.cloud.msg.api.entity.MsgHttpNotifyRecordsEntity;
import com.opencee.cloud.msg.api.vo.DelayedMessage;
import com.opencee.cloud.msg.api.vo.params.HttpNotifyParams;
import com.opencee.cloud.msg.mq.QueueConfiguration;
import com.opencee.cloud.msg.utils.MqUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Map;

@Service
public class HttpNotifyManager {

    @Autowired
    private MsgHttpNotifyRecordsService httpNotifyRecordsService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 发送Http通知
     * 首次是即时推送，重试通知时间间隔为 5s、10s、2min、5min、10min、30min、1h、2h、6h、15h，直到你正确回复状态 200 并且返回 success 或者超过最大重发次数
     */
    public void send(HttpNotifyParams message) throws Exception {
        Assert.hasText(message.getKey(), "key is not empty");
        Assert.hasText(message.getTitle(), "title is not empty");
        Assert.hasText(message.getType(), "type is not empty");
        Assert.hasText(message.getUrl(), "url is not empty");
        if (message.getContent() == null) {
            message.setContent(Maps.newHashMap());
        }
        MsgHttpNotifyRecordsEntity record = new MsgHttpNotifyRecordsEntity();
        record.setTenantId(message.getTenantId());
        record.setTitle(message.getTitle());
        record.setBusinessKey(message.getKey());
        record.setMsgId(IdUtil.simpleUUID());
        record.setUrl(message.getUrl());
        record.setType(message.getType());
        record.setContent(JSONObject.toJSONString(message.getContent()));
        record.setRetryNums(0L);
        record.setResult(0);
        record.setStatus(HttpNotifyState.NORMAL.getValue());
        record.setDelay(0L);
        record.setTotalNums(1L);
        record.setAlertEmail(message.getAlertEmail());
        httpNotifyRecordsService.save(record);
        DelayedMessage delayedMessage = new DelayedMessage(message.getTenantId(), QueueConfiguration.DELAYED_HTTP_NOTIFY_QUEUE_RK, record.getMsgId(), 0, message);
        MqUtil.delayed(amqpTemplate, delayedMessage);
    }


    /**
     * 手动重新发送通知
     *
     * @param id
     */
    public void resend(Long id) throws Exception {
        MsgHttpNotifyRecordsEntity record = httpNotifyRecordsService.getById(id);
        if (record == null) {
            throw new Exception("记录不存在！");
        }
        MsgHttpNotifyRecordsEntity m = new MsgHttpNotifyRecordsEntity();
        m.setId(record.getId());
        m.setStatus(HttpNotifyState.NORMAL.getValue());
        m.setUpdateTime(new Date());
        httpNotifyRecordsService.updateById(m);
        Map<String, Object> data = JSONObject.parseObject(record.getContent(), Map.class);
        HttpNotifyParams msg = new HttpNotifyParams(record.getTenantId(), record.getBusinessKey(), record.getTitle(), record.getUrl(), record.getType(), data, record.getAlertEmail());
        DelayedMessage delayedMessage = new DelayedMessage(record.getTenantId(), QueueConfiguration.DELAYED_HTTP_NOTIFY_QUEUE_RK, record.getMsgId(), 0, msg);
        MqUtil.delayed(amqpTemplate, delayedMessage);
    }


    /**
     * 取消发送
     *
     * @param id
     * @throws Exception
     */
    public void cancel(Long id) throws Exception {
        MsgHttpNotifyRecordsEntity record = httpNotifyRecordsService.getById(id);
        if (record == null) {
            throw new Exception("记录不存在！");
        }
        MsgHttpNotifyRecordsEntity m = new MsgHttpNotifyRecordsEntity();
        m.setId(record.getId());
        m.setStatus(HttpNotifyState.CANCELED.getValue());
        m.setUpdateTime(new Date());
        httpNotifyRecordsService.updateById(m);
    }
}
